/*
* 公共模块
* 图片上传，
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../config/utils");
// 引入日志
const log = require("../log");
// 引入minio
const multer = require('multer');
const fs = require('fs');
const path = require('path');


// 设置路径
const upload = multer({ dest: `img_uploads/${moment().format("YYYY/MM/DD")}` });
const file = "file";

// 上传缩略图
//upload.single()的参数需要是fd中添加的属性名
router.post("/uploadMinio", upload.single(file), (req, res) => {
    console.log("===========上传缩略图接口============");
    // 解析文件名乱码
    let filename = Buffer.from(req.file.originalname, 'latin1').toString('utf8');
    // 设置文件名为时间戳
    let new_filename =   moment().format("YYYYMMDDHHmmss") + "_"+ filename 
    // 获取文件名路径
    let new_path = `${req.file.destination}/${new_filename}`
    // 重命名
    fs.renameSync(req.file.path, new_path);
    // 返回图片URL
    let url = `http://localhost:9984${req.baseUrl}/${new_path}`;
    res.send({
        code: 200, 
        msg: "上传缩略图成功",
        fileName: `${req.baseUrl}/${new_path}`,
        newFileName: new_filename,
        originalFileName: req.file.originalname,
        url: url
    });
})

// 获取图片
let reg2 = /\/img_uploads\/\d{4}\/\d{2}\/\d{2}\/(.*)$/;
router.get(reg2, (req, res) => {
    console.log("===========获取图片接口============")
    // url有中文，需要转码
    let url = decodeURIComponent(req.url);
    // 获取图片路径
    // console.log(process.cwd(),__dirname)
    let path_str = __dirname.replace("\\page\\common", "");
    let path_url = path.join(path_str, url);
    // 读取图片
    fs.readFile(path_url, 'binary', (err, data) => {
        if (err) {
            res.status(404).send({
                code: 404,
                msg: "图片不存在"
            })
            return
        }
        //res.send(data);
        res.writeHead(200, { 'Content-Type': 'image/jpeg' });
        res.write(data, 'binary');
        res.end();
    })
})

// 上传图片
router.post("/upload", upload.single(file), (req, res) => {
    console.log("===========上传缩略图接口============");
    // 解析文件名乱码
    let filename = Buffer.from(req.file.originalname, 'latin1').toString('utf8');
    // 设置文件名为时间戳
    let new_filename =   moment().format("YYYYMMDDHHmmss") + "_"+ filename 
    // 获取文件名路径
    let new_path = `${req.file.destination}/${new_filename}`
    // 重命名
    fs.renameSync(req.file.path, new_path);
    // 返回图片URL
    let url = `http://localhost:9984${req.baseUrl}/${new_path}`;
    res.send({
        code: 200, 
        msg: "上传缩略图成功",
        fileName: `/${new_path}`,
        newFileName: new_filename,
        originalFileName: req.file.originalname,
        url: url
    });
})


module.exports = router;